package com.learning.rpc.config.spring;

import com.learning.rpc.config.ProtocolConfig;
import com.learning.rpc.config.RegistryConfig;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;

import java.lang.reflect.Field;

/**
 * ClassName: RpcConfig
 * Description: 配置类注册器
 * Date: 2022/5/10 23:04 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class RpcConfigRegistrar implements ImportBeanDefinitionRegistrar {
    Environment environment;

    public RpcConfigRegistrar(Environment environment) {
        this.environment = environment;
    }

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        BeanDefinitionBuilder builder;
        
        // ProtocolConfig
        builder = BeanDefinitionBuilder.genericBeanDefinition(ProtocolConfig.class);
        for (Field field : ProtocolConfig.class.getDeclaredFields()) {
            // 从配置文件获取相应匹配的值
            final String property = environment.getProperty("rpc.protocol." + field.getName());
            builder.addPropertyValue(field.getName(), property);
        }
        registry.registerBeanDefinition("protocolConfig", builder.getBeanDefinition());

        // RegistryConfig
        builder = BeanDefinitionBuilder.genericBeanDefinition(RegistryConfig.class);
        for (Field field : RegistryConfig.class.getDeclaredFields()) {
            // 从配置文件获取相应匹配的值
            final String property = environment.getProperty("rpc.registry." + field.getName());
            builder.addPropertyValue(field.getName(), property);
        }
        registry.registerBeanDefinition("registryConfig", builder.getBeanDefinition());
    }
}
